package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SalePlan;
import com.ruoyi.system.domain.Waybills;
import com.ruoyi.system.mapper.SalePlanMapper;
import com.ruoyi.system.mapper.WaybillsMapper;
import com.ruoyi.system.service.ISysDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 首页仪表板Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-10
 */
@Service
public class SysDashboardServiceImpl implements ISysDashboardService 
{
    @Autowired
    private WaybillsMapper waybillsMapper;

    @Autowired
    private SalePlanMapper salePlanMapper;

    /**
     * 获取首页统计数据
     */
    @Override
    public Map<String, Object> getStats()
    {
        Map<String, Object> result = new HashMap<>();
        
        // 运单统计
        Waybills waybillQuery = new Waybills();
        List<Waybills> allWaybills = waybillsMapper.selectWaybillsList(waybillQuery);
        
        // 总运单数
        int totalWaybills = allWaybills.size();
        
        // 今日新增运单
        int todayWaybills = 0;
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String todayStr = sdf.format(today);
        
        // 已完成运单 (waybillState = 4)
        int completedWaybills = 0;
        
        // 待处理运单 (waybillState = 1,2,3)
        int pendingWaybills = 0;
        
        for (Waybills waybill : allWaybills) {
            // 统计今日新增
            if (waybill.getCreateTime() != null) {
                String createDate = sdf.format(waybill.getCreateTime());
                if (todayStr.equals(createDate)) {
                    todayWaybills++;
                }
            }
            
            // 统计状态
            if (waybill.getWaybillState() != null) {
                if (waybill.getWaybillState() == 4) {
                    completedWaybills++;
                } else if (waybill.getWaybillState() >= 1 && waybill.getWaybillState() <= 3) {
                    pendingWaybills++;
                }
            }
        }
        
        // 计算完成率
        int completionRate = totalWaybills > 0 ? (completedWaybills * 100 / totalWaybills) : 0;
        
        // 紧急运单数（待处理的30%）
        int urgentWaybills = (int)(pendingWaybills * 0.3);
        
        // 计划统计
        SalePlan planQuery = new SalePlan();
        List<SalePlan> allPlans = salePlanMapper.selectSalePlanList(planQuery);
        int totalPlans = allPlans.size();
        
        // 活跃计划（state = 1）
        int activePlans = 0;
        for (SalePlan plan : allPlans) {
            if (plan.getState() != null && plan.getState() == 1) {
                activePlans++;
            }
        }
        
        result.put("totalWaybills", totalWaybills);
        result.put("todayWaybills", todayWaybills);
        result.put("totalPlans", totalPlans);
        result.put("activePlans", activePlans);
        result.put("completedWaybills", completedWaybills);
        result.put("completionRate", completionRate);
        result.put("pendingWaybills", pendingWaybills);
        result.put("urgentWaybills", urgentWaybills);
        
        return result;
    }

    /**
     * 获取运单趋势数据
     */
    @Override
    public Map<String, Object> getWaybillTrend(String period)
    {
        Map<String, Object> result = new HashMap<>();
        
        int days = 7;
        if ("30days".equals(period)) {
            days = 30;
        } else if ("90days".equals(period)) {
            days = 90;
        }
        
        List<String> dates = new ArrayList<>();
        List<Integer> salesData = new ArrayList<>();
        List<Integer> purchaseData = new ArrayList<>();
        
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        Calendar calendar = Calendar.getInstance();
        
        // 获取所有运单
        Waybills waybillQuery = new Waybills();
        List<Waybills> allWaybills = waybillsMapper.selectWaybillsList(waybillQuery);
        
        for (int i = days - 1; i >= 0; i--) {
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -i);
            Date date = calendar.getTime();
            String dateStr = sdf.format(date);
            dates.add(dateStr);
            
            // 统计当天的销售和采购运单
            int saleCount = 0;
            int purchCount = 0;
            
            SimpleDateFormat fullSdf = new SimpleDateFormat("yyyy-MM-dd");
            String fullDateStr = fullSdf.format(date);
            
            for (Waybills waybill : allWaybills) {
                if (waybill.getCreateTime() != null) {
                    String waybillDate = fullSdf.format(waybill.getCreateTime());
                    if (fullDateStr.equals(waybillDate)) {
                        // type = 0 销售，type = 1 采购
                        if (waybill.getType() != null) {
                            if (waybill.getType() == 1) {
                                saleCount++;
                            } else if (waybill.getType() == 2) {
                                purchCount++;
                            }
                        } else {
                            saleCount++;  // 默认算销售
                        }
                    }
                }
            }
            
            salesData.add(saleCount);
            purchaseData.add(purchCount);
        }
        
        result.put("dates", dates);
        result.put("salesData", salesData);
        result.put("purchaseData", purchaseData);
        
        return result;
    }

    /**
     * 获取运单状态分布数据
     */
    @Override
    public Map<String, Object> getWaillStatus()
    {
        Map<String, Object> result = new HashMap<>();
        
        Waybills waybillQuery = new Waybills();
        List<Waybills> allWaybills = waybillsMapper.selectWaybillsList(waybillQuery);
        
        // 统计各状态数量
        int state1 = 0;  // 待派车
        int state2 = 0;  // 已派车
        int state3 = 0;  // 运输中
        int state4 = 0;  // 已完成
        int state5 = 0;  // 异常
        
        for (Waybills waybill : allWaybills) {
            if (waybill.getWaybillState() != null) {
                int state = waybill.getWaybillState().intValue();
                switch (state) {
                    case 1:
                        state1++;
                        break;
                    case 2:
                        state2++;
                        break;
                    case 3:
                        state3++;
                        break;
                    case 4:
                        state4++;
                        break;
                    case 5:
                        state5++;
                        break;
                }
            }
        }
        
        List<Map<String, Object>> statusList = new ArrayList<>();
        statusList.add(createStatusItem("待派车", state1, "#409EFF"));
        statusList.add(createStatusItem("已派车", state2, "#67C23A"));
        statusList.add(createStatusItem("运输中", state3, "#E6A23C"));
        statusList.add(createStatusItem("已完成", state4, "#F56C6C"));
        statusList.add(createStatusItem("异常", state5, "#909399"));
        
        result.put("statusData", statusList);
        
        return result;
    }

    /**
     * 获取计划进度数据
     */
    @Override
    public Map<String, Object> getPlanProgress()
    {
        Map<String, Object> result = new HashMap<>();
        
        SalePlan planQuery = new SalePlan();
        List<SalePlan> allPlans = salePlanMapper.selectSalePlanList(planQuery);
        
        List<Map<String, Object>> progressList = new ArrayList<>();
        
        // 取前4个计划作为示例
        int count = 0;
        for (SalePlan plan : allPlans) {
            if (count >= 4) break;
            
            Map<String, Object> item = new HashMap<>();
            item.put("name", plan.getName() != null ? plan.getName() : "未命名计划");
            
            // 使用计划的实际数据
            BigDecimal planQty = plan.getTotal() != null ? plan.getTotal() : new BigDecimal(100);
            BigDecimal completeQty = plan.getCompleted() != null ? plan.getCompleted() : BigDecimal.ZERO;
            
            item.put("total", planQty.longValue());
            item.put("completed", completeQty.longValue());
            
            int percentage = planQty.compareTo(BigDecimal.ZERO) > 0 ? 
                completeQty.multiply(new BigDecimal(100)).divide(planQty, 0, BigDecimal.ROUND_HALF_UP).intValue() : 0;
            item.put("percentage", percentage);
            
            progressList.add(item);
            count++;
        }
        
        // 如果计划少于4个，添加默认数据
        while (progressList.size() < 4) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", "暂无计划数据");
            item.put("total", 0);
            item.put("completed", 0);
            item.put("percentage", 0);
            progressList.add(item);
        }
        
        result.put("progressList", progressList);
        
        return result;
    }

    /**
     * 创建状态项
     */
    private Map<String, Object> createStatusItem(String name, int value, String color)
    {
        Map<String, Object> item = new HashMap<>();
        item.put("name", name);
        item.put("value", value);
        item.put("color", color);
        return item;
    }
}
